package com.foxitcloud.util;

import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

/**
 * @Description spring工具
 * @author xxu
 * @CreateDate 2014年12月8日 下午10:29:54
 */
public class SpringUtil {

    private static volatile ApplicationContext context;

    // static {
    // if (context == null) {
    // context = new
    // ClassPathXmlApplicationContext("classpath*:applicationContext.xml");
    // // SpringApplication appliction = new
    // // SpringApplication(Application.class);
    // // appliction.setWebEnvironment(false);
    // // context = appliction.run(new String[0]);
    // }
    // }

    /**
     * 
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }
    
    public static <T> T getBean(Class<T> requiredType) throws BeansException {
    	return context.getBean(requiredType);
    }


    /**
     * 按特定类型获取Beans集合
     * 
     * @param cls
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> Map<String, T> getBeans(Class<?> cls) {
        return (Map<String, T>) context.getBeansOfType(cls);
    }

    public static void setContext(ApplicationContext ctx) {
        if (context != null) {
            throw new IllegalStateException("ApplicationContext is already setted!");
        }

        context = ctx;
    }
}
